package org.dromara.common.json.config

import com.fasterxml.jackson.databind.Module
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer
import io.github.oshai.kotlinlogging.KotlinLogging
import org.dromara.common.json.handler.BigNumberSerializer
import org.dromara.common.json.handler.CustomDateDeserializer
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder
import java.lang.Long
import java.math.BigDecimal
import java.math.BigInteger
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import kotlin.arrayOf

/**
 * jackson 配置
 *
 * @author Lion Li
 * @updater LikeYouDo
 * @date 2025/1/17 16:55
 */
@AutoConfiguration(before = [JacksonAutoConfiguration::class])
class JacksonConfig {

    companion object {
        private val log = KotlinLogging.logger { }
    }

    @Bean
    fun registerJavaTimeModule(): Module {
        // 全局配置序列化返回 JSON 处理
        val javaTimeModule = JavaTimeModule()
        javaTimeModule.addSerializer(Long::class.java, BigNumberSerializer.INSTANCE)
        javaTimeModule.addSerializer(Long.TYPE, BigNumberSerializer.INSTANCE)
        javaTimeModule.addSerializer(BigInteger::class.java, BigNumberSerializer.INSTANCE)
        javaTimeModule.addSerializer(BigDecimal::class.java, ToStringSerializer.instance)
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
        javaTimeModule.addSerializer(LocalDateTime::class.java, LocalDateTimeSerializer(formatter))
        javaTimeModule.addDeserializer(LocalDateTime::class.java, LocalDateTimeDeserializer(formatter))
        javaTimeModule.addDeserializer(Date::class.java, CustomDateDeserializer())
        return javaTimeModule
    }

    @Bean
    fun customizer(): Jackson2ObjectMapperBuilderCustomizer {
        return Jackson2ObjectMapperBuilderCustomizer { builder: Jackson2ObjectMapperBuilder ->
            builder.timeZone(TimeZone.getDefault())
            log.info { "初始化 jackson 配置" }
        }
    }

}
